package com.morning.aiagentbackend.app;

import com.morning.aiagentbackend.advisor.MyLoggerAdvisor;
import com.morning.aiagentbackend.chatmemory.FileBasedChatMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    private final String SYS_PROMPT =
            "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。围绕单身、恋爱、已婚三种状态提问：" +
                    "单身状态询问社交圈拓展及追求心仪对象的困扰；恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
                    "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。\n";


    public LoveApp(ChatModel dashscopeChatModel) {

        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";

        // 基于文件的对话存储
        FileBasedChatMemory fileBasedChatMemory = new FileBasedChatMemory(fileDir);

        // 基于内存的对话存储
        // InMemoryChatMemory memoryChatMemory = new InMemoryChatMemory();

        this.chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYS_PROMPT)
                .defaultAdvisors(new MessageChatMemoryAdvisor(fileBasedChatMemory), new MyLoggerAdvisor()
                        // new ReReadingAdvisor() 自定义推理增强
                )
                .build();
    }

    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult()
                .getOutput()
                .getText();
        // log.info("content: {}", content);
        return content;
    }

    public record LoveReport(String title, List<String> suggestion) {

    }

    public LoveReport getLoveReport(String message, String chatId) {
        LoveReport entity = chatClient.prompt()
                .system(SYS_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport: {}", entity);
        return entity;
    }

}
